package cn.b.sky.form.controller;

import cn.b.sky.form.constans.CustomerPageConstans;
import cn.b.sky.form.model.BusinessAttachment;
import cn.b.sky.form.service.BusinessAttachmentService;
import cn.b.sky.user.controller.SecurityController;
import cn.b.sky.user.service.AttachmentService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;

/**
 * 
 * <strong>Title : BusinessAttachmentController.java<br></strong>
 * <strong>Package : cn.b.sky.form.controller<br></strong>
 * <strong>Description : </strong>业务对象附件存储<br> 
 * <strong>Create on : 2016-11-24 下午7:34:54<br></strong>
 * <p>
 * @author lidapeng<br>
 * @version <strong>v1.0.0</strong><br>
 * <br>
 * <strong>修改历史:</strong><br>
 * 修改人|修改日期|修改描述<br>
 * -------------------------------------------<br>
 * <br>
 * <br>
 */
@Controller
@RequestMapping("/businessAttach/*")
public class BusinessAttachmentController extends SecurityController {

  @Resource
  private BusinessAttachmentService businessAttachmentService;

  @Resource
  AttachmentService attachmentService;

  @RequestMapping(value = "saveAttachment")
  public void saveAttachment(HttpServletRequest request, HttpSession session, BusinessAttachment attachment,
                             HttpServletResponse response) throws IOException {
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
    String businessType = request.getParameter(CustomerPageConstans.BUSINESSTYPE);
    response.setContentType("application/json;charset=UTF-8");
    for(Entry<String, MultipartFile> entry : fileMap.entrySet()){
      MultipartFile file = entry.getValue();
      attachment.setSiteCode(getSiteCode());
      attachment.setBusinessType(businessType);
      attachment.setBusinessField(entry.getKey());
      attachment = businessAttachmentService.saveBusinessAttachmentAttach(attachment, file);
      response.getWriter().print(JSONObject.toJSONString(ajaxDone(attachment)));
    }
  }
}
